import fs from "node:fs";
import path from "node:path";
import { IS_DEV } from "@elec/main/util/env.ts";

export class FileOutputStream {
  private readonly _file: string;
  private _stream: fs.WriteStream;

  constructor(file: string) {
    const dir = path.dirname(file);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    this._file = file;
    this._stream = fs.createWriteStream(file, { flags: "w" });
    this._stream.on("open", () => {
      if (IS_DEV) {
        console.log(`[FileOutputStream] opened file: ${this._stream.path}`);
      }
    });
    this._initSteam();
  }

  private _initSteam() {
    this._stream.on("error", err => {
      console.error(`[FileOutputStream] error: ${err}`);
    });
  }

  write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean;
  write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean;

  write(chunk: any, ...args: any[]): boolean {
    return this._stream.write(chunk, ...args);
  }

  flush(): Promise<void> {
    return new Promise((resolve, reject) => {
      this._stream.once("error", reject);
      // 关闭并销毁当前流
      this._stream.end(() => {
        this._stream.removeListener("error", reject);
        this._stream.close(err => {
          if (err) {
            console.log(`[FileOutputStream] close error: ${err}`);
          }
          this._stream.destroy();

          // 创建新的流
          this._stream = fs.createWriteStream(this._stream.path, { flags: "a" });
          this._stream.once("open", () => resolve());
          this._stream.once("error", reject);
          this._initSteam();
        });
      });
    });
  }

  close() {
    this._stream.close();
    console.log(`[FileOutputStream] closed file: ${this._file}`);
  }
}
